package com.boe.hbd.client.service.support;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.boe.hbd.client.service.ConfigurationService;

public class FileBasedConfigurationService implements ConfigurationService {
	private static final String TAG = "FileBasedConfigurationService";
	public static final String CONFIG_FILE_NAME = "boe_config.properties";

	private Map<String, String> attributes = new HashMap<String, String>();
	private boolean initialized = false ;
	
	public void save(String configKey, Long configVal) {
		save(configKey, configVal == null ? "" : configVal.toString());
	}

	public Long get(String configKey, Long defaultVal) {
		String val = get(configKey, defaultVal == null ? "" : defaultVal.toString());
		if (val != null) {
			return Long.parseLong(val);
		}
		return null;
	}

	public String get(String configKey, String defaultVal) {
		if (configKey != null && attributes.containsKey(configKey)) {
			return attributes.get(configKey);
		}
		return defaultVal;
	}

	public void save(String configKey, String configVal) {
		if (configKey != null) {
			if (configVal == null) {
				if (attributes.containsKey(configKey)) {
					attributes.remove(configKey);
				}
			} else {
				attributes.put(configKey, configVal);
			}
		}
	}

	public void initialize(Context context) {
		try {
			initialized = true ;
			InputStream stream = context.openFileInput(CONFIG_FILE_NAME);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
			String strLine;
			while ((strLine = bufferedReader.readLine()) != null) {
				String[] tokens = strLine.split("\\=");
				if (tokens.length == 2) {
					attributes.put(tokens[0], tokens[1]);
				}
			}
			stream.close();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		} 
	}

	public void destroy(Context context) {
		try {
			StringBuffer strBuffer = new StringBuffer();
			for (Map.Entry<String, String> pair : attributes.entrySet()) {
				strBuffer.append(pair.getKey() + "=" + pair.getValue() + "\n");
			}
			OutputStream stream = context.openFileOutput(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
			stream.write(strBuffer.toString().getBytes());
			stream.flush();
			stream.close();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		} 
	}

	public void delete(Context context) {
		context.deleteFile(CONFIG_FILE_NAME);
	}

	public boolean isInitialized() {
		return initialized;
    }

	public void pause(Context context) {
    }

	public void resume(Context context) {
    }
}
